package com.evanp.centre.user.controller;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.evanp.centre.user.model.bo.TtiBo;
import com.evanp.centre.user.model.bo.UserBo;
import com.evanp.centre.user.model.bo.UserRegisterBo;
import com.evanp.centre.user.model.dto.UserLoginDto;
import com.evanp.centre.user.model.dto.UserRegisterDto;
import com.evanp.centre.user.model.dto.UserUpdateDto;
import com.evanp.centre.user.model.po.Address;
import com.evanp.centre.user.model.po.SaTokenPayloads;
import com.evanp.centre.user.model.po.User;
import com.evanp.centre.user.model.vo.Client;
import com.evanp.centre.user.service.UserService;
import com.evanp.centre.user.service.UserUtilService;
import com.evanp.centre.user.util.Mapx;
import com.evanp.centre.util.ResBuilder;
import com.google.gson.Gson;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;
    @Resource
    private UserUtilService userUtilService;

    /*
     * @Author Evanpatchouli
     * @see <a href="http://localhost:29999/save"  method="POST">用户注册接口</a>
     * @Description 用户注册接口，接收body，不允许用户名特殊字符，密码不允许中文，电话号码在正常的号段和长度
     * @Return Result code:200成功，400失败
     * */
    @PostMapping("/save")
    public Map regiter(@RequestBody UserRegisterDto userRegisterDto){
        Map err = userUtilService.check_register(userRegisterDto);
        if (err!=null){
            return err;
        }
        UserBo userBo = new UserBo()
            .inject_register(userRegisterDto)
            .encipher_pwd();
        Map options = new HashMap();
        options.put("uname",userBo.getUname());
        if(userService.sel_count_options(options)!=0){
            return ResBuilder.fail("注册失败，该用户已存在");
        }
        TtiBo ttiBo = new TtiBo().inject(userRegisterDto,userBo);
        System.out.println(ttiBo);
        Address address = Address.inject_by_register(userRegisterDto);
        UserRegisterBo userRegisterBo = new UserRegisterBo(userBo, ttiBo, address);
        System.out.println(userRegisterBo);
        userService.register_one(userRegisterBo);

        return ResBuilder.ok("注册成功！");
    }

    /*
     * @Author Evanpatchouli
     * @see <a href="http://localhost:29999/seller"  method="GET">获取商家数接口</a>
     * @Description 获取商家数接口
     * @Return Map 键num对应商家数，若为1，前端注册时应不在给出商家的身份选项
     * */
    @GetMapping("/seller")
    public Map get_seller_num(){
        Map rs = new HashMap();
        int num = userService.sel_seller_count();
        rs.put("num",num);
        return rs;
    }

    /*
     * @Author Evanpatchouli
     * @see <a href="http://localhost:29999/login2"  method="POST">用户登录接口</a>
     * @Description 用户登录接口，接收body
     * @Param userLoginDto user登录DTO
     * @Return Map 键与Result相当,code:401数据不完整，400密码错误，200成功
     * */
    @PostMapping("/login2")
    public Map login(@RequestBody UserLoginDto userLoginDto){
        Map err = userUtilService.check_login(userLoginDto);
        if (err!=null){
            return err;
        }
        UserBo userBo = new UserBo().inject_login(userLoginDto).encipher_pwd();
        Map options = new HashMap();
        options.put("uname", userBo.getUname());
        options.put("upwd", userBo.getUpwd());
        User user_selected = userService.sel_all_options(options);
        if (user_selected==null){
            return ResBuilder.fail("用户名或密码错误");
        }
        Gson gson = new Gson();
        SaTokenPayloads userInfo = new SaTokenPayloads(user_selected.getUid(), user_selected.getUname(), user_selected.getUtype());
        String userInfoJson = gson.toJson(userInfo);
        StpUtil.login(userInfoJson);
        System.out.println("登录用户ID：" + user_selected.getUid());
        Map data = Mapx.first("loginId", StpUtil.getLoginId())
                .set("tokenValue", StpUtil.getTokenValue());
        return ResBuilder.ok("登录成功",0, data);
    }

    // 注销  ---- http://localhost:29999/logout
    @RequestMapping("logout")
    public SaResult logout() {
        StpUtil.logout();
        return SaResult.ok();
    }

    // 查询登录状态，浏览器访问： http://localhost:29999/user/isLogin
    @RequestMapping("isLogin")
    public String isLogin() { return "" + StpUtil.isLogin(); }

    /*
     * @Author Evanpatchouli
     * @see <a href="http://localhost:8080/updatePwd"  method="POST">修改密码接口</a>
     * @Description 修改密码接口，接收body
     * @Param userUpdateDto user改密DTO
     * @Return Result 键code:'400'失败, '200'成功
     * */
    @PostMapping("/updatePwd")
    public Map upd_pwd(@RequestBody UserUpdateDto userUpdateDto){
        Map err = userUtilService.check_upd_pwd(userUpdateDto);
        if (err!=null){
            return err;
        }
        UserBo userBo = new UserBo()
            .inject_upd_pwd(userUpdateDto)
            .encipher_pwd();
        Map options = new HashMap();
        options.put("uname", userBo.getUname());
        options.put("upwd", userBo.getUpwd());
        int user_selected = userService.sel_count_options(options);
        if (user_selected==0){
            return ResBuilder.fail("修改失败，用户名或原密码错误！");
        }
        userBo.setUpwd(userUpdateDto.getUpwd2());
        userBo = userBo.encipher_pwd();
        userService.upd_one_pwd(userBo);

        return ResBuilder.ok("密码修改成功！");
    }

    /*
     * @Author Evanpatchouli
     * @see <a href="http://localhost:29999/selectUserByUid"  method="get">根据uid查询用户接口</a>
     * @Description 根据uid查询用户接口，接收1个路径参数
     * @Param uid 必填，用户id
     * @Return Result 400败，200成功
     * */
    @GetMapping("/selectUserByUid")
    public Map selectUserByUid(@RequestParam String uid){
        User user = userService.sel_all_by_id(uid);
        if(user!=null){
            return ResBuilder.ok("根据uid获取用户信息成功！",0, user);
        }
        return ResBuilder.fail("根据uid获取用户信息失败！");
    }

    /*
     * @Author Evanpatchouli
     * @see <a href="http://localhost:8080/clients"  method="GET">分页获取客户列表接口</a>
     * @Description 分页获取客户列表接口
     * @Param pageNum 当前页数
     * @Param pageSize 页容量
     * @Return Map 键与Result相当
     * */
    @GetMapping("/clients")   //http://localhost:8000/clients
    public Map getClients(@RequestParam Integer pageNum,@RequestParam Integer pageSize){
        Map err = userUtilService.check_get_clients(pageNum, pageSize);
        if (err!=null){
            return err;
        }
        List<Client> clist = userService.sel_clients_by_page(pageNum,pageSize);
        return ResBuilder.ok("获取成功！", 0, clist);
    }


}
